#!/usr/bin/perl

use strict;
use LWP::UserAgent;
use Crypt::SSLeay;
use JSON;
use HTTP::Cookies;
use HTTP::Status;
use Data::Dumper;

my $browser = LWP::UserAgent->new;
$browser->protocols_allowed( [ 'http', 'https'] );
my $cookieFile = "addama_lwp_cookies.dat";
my $cookie_jar = HTTP::Cookies->new(
    file => $cookieFile,
  );
$cookie_jar->load($cookieFile);  
$browser->cookie_jar($cookie_jar);
$browser->timeout(100);
$browser->env_proxy;

if ($#ARGV+1 != 2) {
  die "A file url and output file path are required to run a GET command.  Example usage:\n  perl $0 http://yourhost/addama-rest/myRepo/path/somePath/file.dat /local/myPath/file.dat\n";
  #exit(0);
}
#if ($#ARGV+1 != 4){
#   die "You need to pass in directoryPath, fileType ([all = all files(includes sub directories)][ *.gif,*.png = only gif and png]], hostName and uri\n, I.E.: POST_Files.pl /local/myDirectory *.gif http://server:8080 /addama-rest/sept_repo/path/uploadFolder"
#}
#my ($fileDir, $fileType, $host, $uri) = @ARGV;

my ($url, $fileOut) = @ARGV;

my $json = new JSON;
my $obj;
getUrl($url);


sub getUrl {
  my ($url) = @_;
  if($url) {
      my $response = $browser->get($url);

      if ($response->is_success) {
          my $myContent = $response->content;
          open FILE, ">$fileOut" or die $!; 
          print FILE $myContent; 
          close FILE;
          print "\nFile $fileOut saved and closed\n";
          ## eval in case response isn't legit json
          #eval { $obj = $json->decode($response) };
          #if (! $@) {
          #	print $response;
          #} else {
          #	print Dumper $obj;
          #} 
      }
      else {
          if($response->code()==401) {
            print "\nLogin is required, please run AddamaLogin.pl and try again.\n\n"
          } else {
            die $response->status_line;
          }
      }
  }
}

